<!-- Draggable.vue -->
<template>
    <div ref="draggableElement" class="drag-wrap"
        :style="{ top: dragPosition.top + 'px', left: dragPosition.left + 'px' }" @mousedown="handleMouseDown">

        <!-- 这里是可拖动的内容 -->
        <slot></slot>

    </div>
</template>
  
  <script>
import { ref, reactive } from 'vue';

export default {
    props: {
        initialTop: {
            type: Number,
            default: 0,
        },
        initialLeft: {
            type: Number,
            default: 0,
        },
        handle: {
            type: String,
            default: null,
        }
    },
    setup(props) {
        const dragPosition = reactive({
            top: props.initialTop,
            left: props.initialLeft,
        });

        let isDragging = false;
        let initialMouseOffset = { x: 0, y: 0 };

        function handleMouseDown(event) {

            // console.log("鼠标点击时：", event)
            // console.log("鼠标点击时：", event.target)

            let target = event.target;
            if (props.handle != null) {
                if (target.className.indexOf(props.handle) == -1) return
            }

            // alert("!!");
            if (event.button !== 0) return; // 只处理主鼠标按钮（通常是左键）

            isDragging = true;
            initialMouseOffset.x = event.clientX - dragPosition.left;
            initialMouseOffset.y = event.clientY - dragPosition.top;

            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', handleMouseUp);
        }

        function handleMouseMove(event) {
            if (!isDragging) return;
            dragPosition.left = event.clientX - initialMouseOffset.x;
            dragPosition.top = event.clientY - initialMouseOffset.y;
        }

        function handleMouseUp() {
            isDragging = false;
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        }

        return {
            dragPosition,
            handleMouseDown,
        };
    },
};
</script>


<style lang="less" scoped>
.drag-wrap {
    position: absolute;
    width: auto;
    height: auto;
}
</style>